package com.xunmall.common.service.impl;

import com.google.protobuf.ServiceException;
import com.xunmall.base.util.RandomUtils;
import com.xunmall.base.util.StringUtils;
import com.xunmall.common.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author wangyanjing
 * @date 2020/4/13
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisService redisService;


    @Override
    public String createToken() {
        String str = RandomUtils.generateString(32);
        StringBuilder token = new StringBuilder();
        try {
            token.append("auto").append(str);
            redisService.setEx(token.toString(), token.toString(), 10000L);
            boolean notEmpty = StringUtils.isNotEmpty(token.toString());
            if (notEmpty) {
                return token.toString();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean checkToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader("access_token");
        if(StringUtils.isBlank(token)){
            token = request.getParameter("access_token");
            if (StringUtils.isBlank(token)){
                throw new ServiceException("请传递token");
            }
        }
        if (!redisService.exists(token)){
            throw new ServiceException("token对应KEY不存在");
        }
        boolean remove = redisService.remove(token);
        if(!remove){
         throw new ServiceException("token不存在");
        }
        return true;
    }
}
